package downloader

import (
	"gitee.com/lq8152/myspider/page"
	"gitee.com/lq8152/myspider/request"
	"net/http"
	"net/url"
	"golang.org/x/net/html/charset"
	"strings"
)


type HttpDownloader struct {

}

func NewHttpDownloader() *HttpDownloader {
	return &HttpDownloader{}
}

func (this *HttpDownloader) Download(req *request.Request) *page.Page {
	var mtype string
	var p = page.NewPage(req)
	mtype = req.GetReponseType()
	switch mtype {
	case "html":
		return this.downloadHtml(p,req)
	default:

	}

	return p
}

func (this *HttpDownloader) downloadHtml(page *page.Page, req *request.Request) *page.Page {
		var err error
		page, destbody := this.downloadFile(page, req)
		if !page.IsSucc() {
			return page
		}

		bodyReader := bytes.NewReader([]byte(destbody))

		var doc *goquery.Document
		if doc, err = goquery.NewDocumentFromReader(bodyReader); err !=nil {
			page.SetStatus(true, err.Error())
			return page
		}

		var body string
		if body, err = doc.Html(); err != nil {
			page.SetStatus(true, err.Error())
			return page
		}

		page.SetBodyStr(body).SetHtmlParser(doc).SetStatus(false,"")
		return page
	}


func (this *HttpDownloader) downloadFile(page *page.Page, req *request.Request) (*page.Page, string){
	var err error
	var urlstr string
	if urlstr = req.GetUrl();len(urlstr) == 0 {
		page.SetStatus(true, "url is empty")
		return page,""
	}

	client := &http.Client{
		CheckRedirect: req.GetRedirectFunc(),
	}
	httpreq, err := http.NewRequest(req.GetMethod(),req.GetUrl(),strings.NewReader(req.GetPostdata()))
	if header := req.GetHeader(); header != nil {
		httpreq.Header = req.GetHeader()
	}

	if cookies := req.GetCookies(); cookies != nil {
		for i := range cookies {
			httpreq.AddCookie(cookies[i])
		}
	}

	var resp *http.Response
	if resp, err = client.Do(httpreq); err != nil {
	   if e, ok := err.(*url.Error); ok && e.Err !=nil && e.Err.Error() == "normal" {

	   }else{
		   page.SetStatus(true, err.Error())
		   return page, ""
	   }
	}
	page.SetHeader(resp.Header)
	page.SetCookies(resp.Cookies())

	bodyStr := this.changeCharsetEncodingAuto(resp.Header.Get("Content-Type"),resp.Body)
	defer resp.Body.Close()
	return page,bodyStr

}

func (this *HttpDownloader) changeCharsetEncodingAuto(contentTypeStr string , sor io.ReadCloser) string {
	var err error
	destReader, err := charset.NewReader(sor, contentTypeStr)
	if err != nil {
		destReader = sor
	}
	
	var sorbody []byte
	if sorbody, err := ioutil.ReadAll(destReader); err !=nil {

	}

	bodyStr := string(sorbody)

	return bodystr
}